AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

local rel = "npc/strider/strider_minigun.wav"
util.PrecacheSound(rel)
include('shared.lua')
local Ground = 1 + 0 + 2 + 8 + 32

function ENT:Initialize()
	self.Entity:SetModel(  "models/props_lab/tpplugholder_single.mdl" )
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType(  MOVETYPE_VPHYSICS   )
	self.Entity:SetSolid( SOLID_VPHYSICS )
	self.Entity:SetName("Small.Railgun.50x30")
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end
	table.insert(servertable["ship"]["weapons"],self.Entity)
	self.nextfire = CurTime()
	self.salvo = 0
	self.fire = false
	self.use = false
end

function ENT:SpawnFunction( ply, tr )
	if ( !tr.Hit ) then return end
	local SpawnPos = tr.HitPos + tr.HitNormal * 36
	local ent = ents.Create( "RailGun_1000" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	return ent
end

function ENT:OnRemove()
	if self.core then
		if self.use then core.turrets = core.turrets - 1 end
	end
end

function ENT:Think()
	self.Entity:NextThink( CurTime() + 5 )
	if self.core then
		if  (self.core:IsValid()) then
			if self.fire then
				if (self.nextfire < CurTime()) then
					if not self.use then
						if (self.core.turrets < self.core.maxturrets) then
							if (self.core.capaciator > 150) then
								if (self.core.bullets > 5) then
									if (self.core.heat < 70) then
										if Fieldoffire(self.Entity,120) then
											self.core.heat = self.core.heat + 30
											self.core.capaciator = self.core.capaciator - 150
											self.core.bullets = self.core.bullets - 5
											self.core.turrets = self.core.turrets + 1
											self:EmitSound(rel,500,math.random(80,120))
											self.salvo = 50
											self.use = true
											self.nextfire = CurTime() + 2
										end
									end
								end
							end
						end
					end
				end
			end
			if self.salvo > 0 then
				local Startpos =  self.Entity:GetPos() + (self.correct * 50) 
				bullet = {} 
				bullet.Src		= self.Entity:GetPos() + self.correct*50
				bullet.Dir		= self.correct 
				bullet.Spread		= Vector(0.005,0.005,0.005) 
				bullet.Num		= 1 
				bullet.Damage		= 30 
				bullet.Force		= 1 
				bullet.Tracer		= 2	 
				bullet.TracerName	= "AR2Tracer"
				self.Entity:FireBullets( bullet )
				self.salvo = self.salvo -1
				self.Entity:NextThink( CurTime() + 0.01 )
			else
				if (self.nextfire < CurTime()) then
					if self.use then self.core.turrets = self.core.turrets - 1 self.use = false end
				end
				self.Entity:NextThink( CurTime() + 0.25 )
			end
		else
			self.core = nil
		end
	else
		self.core = getshipcore(self.Entity)
		if not self.core then
			self.Entity:NextThink( CurTime() + 5 )
			return true
		end
	end
	return true
end

function ENT:OnTakeDamage(info)
	Shieldhit(info,self.Entity)
end